<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2D World - 基础使用示例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .content {
            display: grid;
            grid-template-columns: 300px 1fr;
            min-height: 600px;
        }
        
        .sidebar {
            background: #f8f9fa;
            padding: 20px;
            border-right: 1px solid #e9ecef;
        }
        
        .canvas-container {
            position: relative;
            background: #f8f9fa;
        }
        
        canvas {
            display: block;
            background: white;
            cursor: crosshair;
        }
        
        .controls {
            margin-bottom: 30px;
        }
        
        .control-group {
            margin-bottom: 20px;
        }
        
        .control-group h3 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 1.1em;
            font-weight: 600;
        }
        
        .btn {
            display: block;
            width: 100%;
            padding: 12px;
            margin: 5px 0;
            border: none;
            border-radius: 8px;
            background: #3498db;
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn-success {
            background: #27ae60;
        }
        
        .btn-success:hover {
            background: #219a52;
        }
        
        .btn-warning {
            background: #f39c12;
        }
        
        .btn-warning:hover {
            background: #d68910;
        }
        
        .btn-danger {
            background: #e74c3c;
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .status-bar {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(44, 62, 80, 0.9);
            color: white;
            padding: 10px 20px;
            font-size: 14px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .status-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #27ae60;
        }
        
        .status-indicator.error {
            background: #e74c3c;
        }
        
        .tooltip {
            position: absolute;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            pointer-events: none;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .tooltip.show {
            opacity: 1;
        }
        
        .layer-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 10px;
        }
        
        .layer-item {
            padding: 8px 12px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
        }
        
        .layer-item.active {
            background: #e3f2fd;
            border-left: 3px solid #2196f3;
        }
        
        .layer-item:hover {
            background: #f5f5f5;
        }
        
        .history-stack {
            max-height: 150px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 10px;
            font-size: 12px;
        }
        
        .history-item {
            padding: 6px 10px;
            border-bottom: 1px solid #eee;
        }
        
        .history-item:last-child {
            border-bottom: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>2D World 示例</h1>
            <p>交互式2D图形编辑器 - 图层管理与撤销重做演示</p>
        </div>
        
        <div class="content">
            <div class="sidebar">
                <div class="controls">
                    <div class="control-group">
                        <h3>图形创建</h3>
                        <button class="btn" onclick="createRectangle()">创建矩形</button>
                        <button class="btn" onclick="createCircle()">创建圆形</button>
                        <button class="btn" onclick="createPolygon()">创建多边形</button>
                        <button class="btn" onclick="createLine()">创建线条</button>
                    </div>
                    
                    <div class="control-group">
                        <h3>选择操作</h3>
                        <button class="btn" onclick="selectAll()">全选</button>
                        <button class="btn" onclick="clearSelection()">清空选择</button>
                        <button class="btn btn-danger" onclick="deleteSelected()">删除选中</button>
                    </div>
                    
                    <div class="control-group">
                        <h3>变换操作</h3>
                        <button class="btn" onclick="moveSelected(10, 0)">右移 10px</button>
                        <button class="btn" onclick="moveSelected(-10, 0)">左移 10px</button>
                        <button class="btn" onclick="rotateSelected(15)">旋转 15°</button>
                        <button class="btn" onclick="scaleSelected(1.1, 1.1)">缩放 110%</button>
                    </div>
                    
                    <div class="control-group">
                        <h3>图层管理</h3>
                        <button class="btn" onclick="createNewLayer()">新建图层</button>
                        <button class="btn" onclick="setLayerVisibility('layer1', false)">隐藏图层1</button>
                        <button class="btn" onclick="setLayerVisibility('layer1', true)">显示图层1</button>
                        <div class="layer-list" id="layerList">
                            <!-- 图层列表将动态生成 -->
                        </div>
                    </div>
                    
                    <div class="control-group">
                        <h3>撤销重做</h3>
                        <button class="btn btn-warning" onclick="undo()">撤销 (Ctrl+Z)</button>
                        <button class="btn btn-success" onclick="redo()">重做 (Ctrl+Y)</button>
                        <div class="history-stack" id="historyStack">
                            <!-- 历史记录将动态显示 -->
                        </div>
                    </div>
                    
                    <div class="control-group">
                        <h3>视图控制</h3>
                        <button class="btn" onclick="zoomIn()">放大</button>
                        <button class="btn" onclick="zoomOut()">缩小</button>
                        <button class="btn" onclick="resetView()">重置视图</button>
                        <button class="btn" onclick="fitToView()">适应视图</button>
                    </div>
                    
                    <div class="control-group">
                        <h3>数据操作</h3>
                        <button class="btn" onclick="saveWorld()">保存场景</button>
                        <button class="btn" onclick="loadWorld()">加载场景</button>
                        <button class="btn btn-danger" onclick="clearWorld()">清空场景</button>
                    </div>
                </div>
            </div>
            
            <div class="canvas-container">
                <canvas id="worldCanvas" width="800" height="600"></canvas>
                <div class="status-bar">
                    <div class="status-item">
                        <div class="status-indicator"></div>
                        <span id="statusText">就绪</span>
                    </div>
                    <div class="status-item">
                        <span>选中: <span id="selectedCount">0</span> 对象</span>
                        <span>图层: <span id="layerCount">1</span></span>
                        <span>历史: <span id="historyCount">0</span> 步</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="tooltip" id="tooltip"></div>
    
    <script type="module">
        import World from '../src/World.js';
        import { Rectangle, Circle, Polygon, Line } from '../src/shapes/index.js';
        
        // 全局变量
        let world;
        let tooltip = document.getElementById('tooltip');
        
        // 初始化World
        function initializeWorld() {
            const canvas = document.getElementById('worldCanvas');
            
            world = new World(canvas, {
                gridSize: 20,
                gridVisible: true,
                snapToGrid: false,
                backgroundColor: '#f8f9fa'
            });
            
            // 初始化World
            world.initialize();
            
            // 创建默认图层
            world.createLayer('layer1', '默认图层');
            world.setActiveLayer('layer1');
            
            // 添加事件监听
            setupEventListeners();
            
            // 创建一些示例对象
            createSampleObjects();
            
            updateStatus();
            updateLayerList();
            updateHistoryStack();
            
            setStatus('World初始化完成', 'success');
        }
        
        // 设置事件监听器
        function setupEventListeners() {
            // 监听对象添加事件
            world.on('objectAdded', ({ object }) => {
                console.log('对象已添加:', object.id);
                updateStatus();
            });
            
            // 监听对象移除事件
            world.on('objectRemoved', ({ object }) => {
                console.log('对象已移除:', object.id);
                updateStatus();
            });
            
            // 监听选择变化事件
            world.on('selectionChanged', ({ selected }) => {
                document.getElementById('selectedCount').textContent = selected.length;
                updateStatus(`选中 ${selected.length} 个对象`);
            });
            
            // 监听视图变化事件
            world.on('viewChanged', ({ transform }) => {
                console.log('视图变换:', transform);
            });
            
            // 监听历史记录变化
            world.on('historyChanged', () => {
                updateHistoryStack();
                updateStatus();
            });
            
            // 监听图层变化
            world.on('layerChanged', () => {
                updateLayerList();
                updateStatus();
            });
            
            // 鼠标移动显示工具提示
            canvas.addEventListener('mousemove', (e) => {
                const rect = canvas.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;
                
                tooltip.style.left = (e.clientX + 10) + 'px';
                tooltip.style.top = (e.clientY + 10) + 'px';
                
                // 检测鼠标下的对象
                const objects = world.getObjects();
                const hoveredObject = objects.find(obj => {
                    const point = world.viewController.screenToWorld({ x, y });
                    return obj.contains(point);
                });
                
                if (hoveredObject) {
                    tooltip.textContent = `${hoveredObject.type} (${hoveredObject.id})`;
                    tooltip.classList.add('show');
                } else {
                    tooltip.classList.remove('show');
                }
            });
            
            // 键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (e.ctrlKey || e.metaKey) {
                    switch (e.key) {
                        case 'z':
                            e.preventDefault();
                            undo();
                            break;
                        case 'y':
                            e.preventDefault();
                            redo();
                            break;
                        case 'a':
                            e.preventDefault();
                            selectAll();
                            break;
                        case 's':
                            e.preventDefault();
                            saveWorld();
                            break;
                    }
                }
                
                // 删除键
                if (e.key === 'Delete') {
                    e.preventDefault();
                    deleteSelected();
                }
            });
        }
        
        // 创建示例对象
        function createSampleObjects() {
            // 创建矩形
            const rect = new Rectangle(120, 80, {
                position: { x: 200, y: 200 },
                rotation: 0,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: '#3498db',
                strokeColor: '#2980b9',
                strokeWidth: 2
            }, 'layer1');
            
            // 创建圆形
            const circle = new Circle(50, {
                position: { x: 400, y: 300 },
                rotation: 0,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: '#e74c3c',
                strokeColor: '#c0392b',
                strokeWidth: 2
            }, 'layer1');
            
            // 创建多边形
            const polygon = new Polygon([
                { x: 0, y: -40 },
                { x: 40, y: 0 },
                { x: 0, y: 40 },
                { x: -40, y: 0 }
            ], {
                position: { x: 600, y: 200 },
                rotation: 45,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: '#27ae60',
                strokeColor: '#219a52',
                strokeWidth: 2
            }, 'layer1', true);
            
            world.addObject(rect);
            world.addObject(circle);
            world.addObject(polygon);
        }
        
        // 图形创建函数
        function createRectangle() {
            const rect = new Rectangle(80 + Math.random() * 40, 60 + Math.random() * 40, {
                position: { x: 100 + Math.random() * 600, y: 100 + Math.random() * 400 },
                rotation: Math.random() * 360,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: `hsl(${Math.random() * 360}, 70%, 60%)`,
                strokeColor: `hsl(${Math.random() * 360}, 80%, 40%)`,
                strokeWidth: 2
            });
            
            world.addObject(rect);
            setStatus('矩形已创建');
        }
        
        function createCircle() {
            const circle = new Circle(30 + Math.random() * 30, {
                position: { x: 100 + Math.random() * 600, y: 100 + Math.random() * 400 },
                rotation: 0,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: `hsl(${Math.random() * 360}, 70%, 60%)`,
                strokeColor: `hsl(${Math.random() * 360}, 80%, 40%)`,
                strokeWidth: 2
            });
            
            world.addObject(circle);
            setStatus('圆形已创建');
        }
        
        function createPolygon() {
            const sides = 3 + Math.floor(Math.random() * 5);
            const points = [];
            const radius = 30 + Math.random() * 30;
            
            for (let i = 0; i < sides; i++) {
                const angle = (i / sides) * Math.PI * 2;
                points.push({
                    x: Math.cos(angle) * radius,
                    y: Math.sin(angle) * radius
                });
            }
            
            const polygon = new Polygon(points, {
                position: { x: 100 + Math.random() * 600, y: 100 + Math.random() * 400 },
                rotation: Math.random() * 360,
                scale: { x: 1, y: 1 },
                anchor: { x: 0.5, y: 0.5 }
            }, {
                fillColor: `hsl(${Math.random() * 360}, 70%, 60%)`,
                strokeColor: `hsl(${Math.random() * 360}, 80%, 40%)`,
                strokeWidth: 2
            }, undefined, true);
            
            world.addObject(polygon);
            setStatus('多边形已创建');
        }
        
        function createLine() {
            const line = new Line(
                { x: -30, y: 0 },
                { x: 30, y: 0 },
                {
                    position: { x: 100 + Math.random() * 600, y: 100 + Math.random() * 400 },
                    rotation: Math.random() * 360,
                    scale: { x: 1, y: 1 },
                    anchor: { x: 0.5, y: 0.5 }
                },
                {
                    fillColor: 'transparent',
                    strokeColor: `hsl(${Math.random() * 360}, 80%, 40%)`,
                    strokeWidth: 3
                }
            );
            
            world.addObject(line);
            setStatus('线条已创建');
        }
        
        // 选择操作函数
        function selectAll() {
            const objects = world.getObjects();
            objects.forEach(obj => world.select(obj, true));
            setStatus(`已选择所有 ${objects.length} 个对象`);
        }
        
        function clearSelection() {
            world.clearSelection();
            setStatus('选择已清空');
        }
        
        function deleteSelected() {
            const selected = world.getSelectedObjects();
            if (selected.length === 0) {
                setStatus('没有选中对象', 'error');
                return;
            }
            
            selected.forEach(obj => world.removeObject(obj));
            setStatus(`已删除 ${selected.length} 个对象`);
        }
        
        // 变换操作函数
        function moveSelected(dx, dy) {
            const selected = world.getSelectedObjects();
            if (selected.length === 0) {
                setStatus('请先选择对象', 'error');
                return;
            }
            
            world.translateSelected({ x: dx, y: dy });
            setStatus(`已移动 ${selected.length} 个对象`);
        }
        
        function rotateSelected(angle) {
            const selected = world.getSelectedObjects();
            if (selected.length === 0) {
                setStatus('请先选择对象', 'error');
                return;
            }
            
            world.rotateSelected(angle * Math.PI / 180);
            setStatus(`已旋转 ${selected.length} 个对象`);
        }
        
        function scaleSelected(sx, sy) {
            const selected = world.getSelectedObjects();
            if (selected.length === 0) {
                setStatus('请先选择对象', 'error');
                return;
            }
            
            world.scaleSelected(sx, sy);
            setStatus(`已缩放 ${selected.length} 个对象`);
        }
        
        // 图层管理函数
        function createNewLayer() {
            const layerId = 'layer' + (world.getAllLayers().length + 1);
            const layerName = '图层 ' + (world.getAllLayers().length + 1);
            
            world.createLayer(layerId, layerName);
            world.setActiveLayer(layerId);
            setStatus(`已创建新图层: ${layerName}`);
        }
        
        function setLayerVisibility(layerId, visible) {
            if (world.setLayerVisibility(layerId, visible)) {
                setStatus(`图层 ${layerId} ${visible ? '已显示' : '已隐藏'}`);
            } else {
                setStatus('图层操作失败', 'error');
            }
        }
        
        // 撤销重做函数
        function undo() {
            if (world.undo()) {
                setStatus('已撤销上一步操作');
            } else {
                setStatus('无法撤销', 'error');
            }
        }
        
        function redo() {
            if (world.redo()) {
                setStatus('已重做下一步操作');
            } else {
                setStatus('无法重做', 'error');
            }
        }
        
        // 视图控制函数
        function zoomIn() {
            world.zoom(1.2);
            setStatus('视图已放大');
        }
        
        function zoomOut() {
            world.zoom(0.8);
            setStatus('视图已缩小');
        }
        
        function resetView() {
            world.resetView();
            setStatus('视图已重置');
        }
        
        function fitToView() {
            world.fitToView();
            setStatus('视图已适应对象');
        }
        
        // 数据操作函数
        function saveWorld() {
            const worldData = world.serialize();
            localStorage.setItem('worldData', JSON.stringify(worldData));
            setStatus('场景数据已保存到本地存储');
        }
        
        function loadWorld() {
            const savedData = localStorage.getItem('worldData');
            if (savedData) {
                try {
                    const worldData = JSON.parse(savedData);
                    world.deserialize(worldData);
                    setStatus('场景数据已从本地存储加载');
                } catch (error) {
                    setStatus('加载失败: ' + error.message, 'error');
                }
            } else {
                setStatus('没有找到保存的数据', 'error');
            }
        }
        
        function clearWorld() {
            const objects = world.getObjects();
            objects.forEach(obj => world.removeObject(obj));
            setStatus('场景已清空');
        }
        
        // 状态更新函数
        function updateStatus(message = '', type = '') {
            const statusText = document.getElementById('statusText');
            const indicator = document.querySelector('.status-indicator');
            
            if (message) {
                statusText.textContent = message;
            } else {
                const objects = world.getObjects();
                const layers = world.getAllLayers();
                statusText.textContent = `场景: ${objects.length} 对象, ${layers.length} 图层`;
            }
            
            if (type === 'error') {
                indicator.classList.add('error');
                setTimeout(() => {
                    indicator.classList.remove('error');
                }, 2000);
            }
            
            // 更新计数
            document.getElementById('selectedCount').textContent = world.getSelectedObjects().length;
            document.getElementById('layerCount').textContent = world.getAllLayers().length;
            document.getElementById('historyCount').textContent = 
                (world.historyManager?.undoStack?.length || 0) + (world.historyManager?.redoStack?.length || 0);
        }
        
        function setStatus(message, type = '') {
            updateStatus(message, type);
        }
        
        // 更新图层列表
        function updateLayerList() {
            const layerList = document.getElementById('layerList');
            const layers = world.getAllLayers();
            const activeLayer = world.getActiveLayer();
            
            layerList.innerHTML = '';
            
            layers.forEach(layer => {
                const item = document.createElement('div');
                item.className = 'layer-item' + (layer.id === activeLayer?.id ? ' active' : '');
                item.innerHTML = `
                    <span>${layer.name}</span>
                    <span style="color: ${layer.visible ? '#27ae60' : '#e74c3c'}">
                        ${layer.visible ? '可见' : '隐藏'}
                    </span>
                `;
                
                item.addEventListener('click', () => {
                    world.setActiveLayer(layer.id);
                    updateLayerList();
                });
                
                layerList.appendChild(item);
            });
        }
        
        // 更新历史记录堆栈
        function updateHistoryStack() {
            const historyStack = document.getElementById('historyStack');
            const historyManager = world.historyManager;
            
            if (!historyManager) {
                historyStack.innerHTML = '<div class="history-item">历史记录不可用</div>';
                return;
            }
            
            historyStack.innerHTML = '';
            
            // 显示最近的5条历史记录
            const recentHistory = [...historyManager.undoStack].slice(-5).reverse();
            
            recentHistory.forEach(record => {
                const item = document.createElement('div');
                item.className = 'history-item';
                item.textContent = `${record.type} - ${record.objects?.length || 0} 对象`;
                historyStack.appendChild(item);
            });
            
            if (recentHistory.length === 0) {
                historyStack.innerHTML = '<div class="history-item">暂无历史记录</div>';
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initializeWorld);
    </script>
</body>
</html>